<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <!-- 左侧 -->
          <el-tab-pane label="角色管理" name="role">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showAddRoleDialog"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="100" prop="id" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <!--
              current-page:当前页
              page-sizes:设置当前页的页容量
              page-size:当前页的页容量
              layout：分页的布局
              total:一共多少条
              @size-change  切换页容量的时候会执行该事件
               @current-change 切换页码触发事件
             -->
            <div style="padding: 10px; display: flex; justify-content: flex-end;">
              <el-pagination
                :current-page="page"
                :page-sizes="[1, 2, 3, 4,5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>

          <!-- 公司信息 -->
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :visible="showDialog" :title="showTitle" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="addRoles">确认</el-button>
        </template>
      </el-dialog>

      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" @open="openAssignDialog">
        <!-- show-checkbox:节点是否可被选择 -->
        <!-- check-strictly 有复选框的情况下 父和子不关联 -->
        <el-tree
          ref="tree"
          :data="permissionData"
          :props="{ label: 'name' }"
          :show-checkbox="true"
          :check-strictly="true"
          :default-expand-all="true"
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="editRolePermission">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleList, delRole, addRole, getRole, editRole, editRolePermissionApi } from '@/api/setting'
import { mapState } from 'vuex'
import { getCompanyApi } from '@/api/company'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Dashboard',
  data() {
    return {
      list: [],
      page: 1,
      pagesize: 2,
      // 列表总和
      total: 0,
      loading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      },
      activeName: 'role',
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        refmarks: ''
      },
      showAssignDialog: false, // 控制弹层的显示隐藏
      roleId: '', // 记录正在操作的角色
      permissionData: [] // 存储权限数据
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '修改角色' : '新增角色'
    }
  },
  // watch: {
  //   activeName(newval, oldval) {
  //     console.log(newval)
  //     if (newval === 'company') {
  //       this.getCompanyInfo()
  //     }
  //   }
  // },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      // 多级解构
      this.loading = true
      const { data: { rows, total }} = await getRoleList(this.page, this.pagesize)
      console.log('获取角色列表成功', rows, total)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    indexMethod(index) {
      // (this.page - 1) * this.pagesize 表示的是上一页所有的数据的总和
      return (this.page - 1) * this.pagesize + index + 1
    },
    delRole(id) {
      this.$confirm('亲,你确定要删除吗', '温馨提示').then(async() => {
        const res = await delRole(id)
        this.$message.success('删除成功', res)
        // 如果当前页码大于1 并且 当前页只有一条的数据就刷新到上一页的数据
        if (this.page > 1 && this.list.length === 1) {
          this.page--
        }
        this.getRoleList()
      }).catch(err => {
        console.log(err)
      })
    },
    showAddRoleDialog() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    addRoles() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          const res = await editRole(this.form)
          console.log('修改角色成功', res)
          // 提示
          this.$message.success('修改成功')
        } else {
          const res = await addRole(this.form)
          console.log('添加成功', res)
          this.$message.success('添加成功')
        }
        // 关闭弹框
        this.closeDialog()
        // 刷新数据
        this.getRoleList()
      })
    },
    async editRole(id) {
      this.showDialog = true
      const { data } = await getRole(id)
      console.log('获取角色详情成功', data)
      this.form = data
    },
    async getCompanyInfo() {
      const { data } = await getCompanyApi(this.userInfo.companyId)
      console.log('获取公司详情成功', data)
      this.companyForm = data
    },
    closeAssignDialog() {
      this.showAssignDialog = false
      // 数据清空
      this.$refs.tree.setCheckedKeys([])
    },
    async getPermissionList() {
      const { data } = await getPermissionListApi()
      console.log('获取权限列表成功', data)
      this.permissionData = transListToTreeData(data, '0')
    },
    async openAssignDialog() {
      // 获取所有权限的列表
      this.getPermissionList()
      // 获取角色拥有的列表
      const { data: { permIds }} = await getRole(this.roleId)
      console.log('获取角色拥有的权限成功', permIds)
      // 默认回显 必须传node-key作为唯一标识
      this.$refs.tree.setCheckedKeys(permIds)
    },
    async clickShowAssignDialog(id) {
      this.showAssignDialog = true
      this.roleId = id
    },
    async editRolePermission() {
      const res = await editRolePermissionApi({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      console.log('分配权限成功', res)
      this.closeAssignDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
    // 弹窗信息
    ::v-deep
    .el-dialog__header {
    background: #66b1ff;

    .el-icon-close:before {
      color: #fff;
    }

    .el-dialog__title {
      color: #fff;
    }

  }
</style>
